package model

import (
	"common/helper"
	"database/sql"
	"fmt"
	g "github.com/doug-martin/goqu/v9"
)

func PromoDepositConfigInsert(data PromoDepositConfig) error {

	data.Id = helper.GenId()
	query, _, _ := dialect.Insert("tbl_promo_deposit").Rows(&data).ToSQL()
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	return nil
}

func PromoDepositConfigUpdate(id string, data PromoDepositConfig) error {

	query, _, _ := dialect.Update("tbl_promo_deposit").Set(&data).Where(g.Ex{"id": id}).ToSQL()

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	return nil
}

func PromoDepositConfigDelete(id string, data PromoDepositConfig) error {

	query, _, _ := dialect.Delete("tbl_promo_deposit").Where(g.Ex{"id": id}).ToSQL()

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	return nil
}

func PromoDepositConfigList(page, pageSize uint, ex g.Ex) (PromoDepositConfigData, error) {

	data := PromoDepositConfigData{}
	t := dialect.From("tbl_promo_deposit")
	if page >= 1 {
		query, _, _ := t.Select(g.COUNT(1)).Where(ex).ToSQL()

		err := meta.MerchantDB.Get(&data.T, query)
		if err != nil {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}

	offset := (page - 1) * pageSize
	query, _, _ := t.Select(colsPromoDepositConfig...).Where(ex).Offset(offset).Limit(pageSize).Order(g.C("sort").Asc()).ToSQL()

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	data.S = pageSize
	return data, nil
}
